<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
/**
 * Prunus Grilla
 *
 * Clase para encapsular jQuery Grid Plugin [http://www.trirand.com/blog/]
 *
 * @author		agosto
 * @date		  20090704
 * @version		0.1
 * @copyright	Copyright (c) 2009, 7dedos
 * @link		http://www.7dedos.com.ar
 */
 
/* Estructura del array DATA ******************************************************************************
  $id - No es un elemento del array, es la clave de cada item
  $dataSourceUri - uri con el origen de datos para la grilla
  $title - titulo de la grilla
  $ancho - ancho de la grilla en pixeles(solo nro) o porcentaje(solo nro con el signo % al final). por default es 100%
  $recordsPerPage - canitdad default de registros por pagina de la grilla *CONFIG*
  $recordsPerPageList - lista de posibles valores para q el usuario elija los registros por pagina *CONFIG*
  $defaultOrderFieldId - campo default por el q se ordenara la grilla
  $defaultOrderDirection - direccion de ordenamiento que se aplicara al campo $defaultOrderFieldId de la grilla
  $fields - array con lo campos de la grilla. cada registro es un array con los siguientes valores:
    name
    label
    align  (opcional - default left)
    width  (opcional - ancho automatico)
*/

include_once ('prunus_buffer.php');

class prunus_grilla {
	private $ci;
  private $buffer;
  private $actions; //para el pie
  private $data; //array principal
  private $widthBorders = 0;
  
	public function __construct()	{
		$this->ci =& get_instance();
    $this->ci->load->helper('form');
    $this->ci->load->config('prunus_grilla');
    $this->buffer = new prunus_buffer($this->ci->config->item('PRGR_defaultOffset'));
   
		log_message('debug', 'prunus_grilla inicializado');
	}
  
  //getters & setter
  //public function RecordsPerPage() { return $this->recordsPerPage; } 

  
  public function create ($gridId, $title, $dataSourceUri, $recPerPage = null, $orderFieldId = null, $orderDirection = null, $recPerPageList = null) {
    $this->data[$gridId]['fields'] = array();
    $this->data[$gridId]['title'] = $title;
    $this->data[$gridId]['dataSourceUri'] = $dataSourceUri;
    $this->data[$gridId]['overrideView'] = null;
    $this->data[$gridId]['overrideSelect'] = null;
    $this->data[$gridId]['width'] = '100%';
    if ($orderFieldId !== null)  { $this->data[$gridId]['defaultOrderFieldId'] = $orderFieldId; }     else { $this->data[$gridId]['defaultOrderFieldId'] = null; }
    if ($orderDirection !== null){ $this->data[$gridId]['defaultOrderDirection'] = $orderDirection; } else { $this->data[$gridId]['defaultOrderDirection'] = 'asc'; }
    if ($recPerPage !== null)    { $this->data[$gridId]['recordsPerPage'] = $recPerPage;  }           else { $this->data[$gridId]['recordsPerPage'] = $this->ci->config->item('PRGR_defaultRecordsPerPage'); }
    if ($recPerPageList !== null){ $this->data[$gridId]['recordsPerPageList'] = $recPerPageList; }    else { $this->data[$gridId]['recordsPerPageList'] = $this->ci->config->item('PRGR_defaultRecordsPerPageList'); }
    $this->data[$gridId]['pager']['refresh']  = true;
    $this->data[$gridId]['pager']['edit']  = false;
    $this->data[$gridId]['pager']['add']  = false;
    $this->data[$gridId]['pager']['del']  = false;
    $this->data[$gridId]['pager']['search']  = false;
    $this->data[$gridId]['pager']['view']  = false;
  }
  public function setWidthPixel ($gridId, $width)   { $this->data[$gridId]['width'] = $width; }
  public function setWidthPercent ($gridId, $width) { $this->data[$gridId]['width'] = $width; }
  
  public function overrideView($gridId, $url)   { $this->data[$gridId]['overrideView']   = $url; $this->data[$gridId]['pager']['view']  = true; }
  public function overrideSelect($gridId, $url) { $this->data[$gridId]['overrideSelect'] = $url; }
  
  public function addField($gridId, $fieldId, $name, $label, $align = 'left', $width = null) { $this->data[$gridId]['fields'][$fieldId] = array('name'=>$name, 'label'=>$label, 'align'=>$align, 'width'=>$width); }
  public function addAction ($uri,$text,$onclick='') { $this->actions[] = array($uri,$text,$onclick); }

  public function setPagerButtons ($gridId,$buttons) {
    foreach ($buttons as $id => $value) $this->data[$gridId]['pager'][$id]  = $value;
  }
  
  public function renderContainerDiv($gridId) {
    $this->buffer->clear();
    $this->buffer->addLine(0, "<div class=\"PRGR_container\">");
    $this->buffer->addLine(2, "<table id=\"" . $gridId. "\" class=\"scroll\" summary=\"\"><tr><td></td></tr></table> ");
    $this->buffer->addLine(2, "<div id=\"" . $gridId . "_pager\" class=\"scroll\" style=\"text-align:center;\"></div>");
    $this->buffer->addLine(0, "</div>");
    return $this->buffer->get();
  }
  
  public function render() {
    $this->buffer->clear();
    
    $this->buffer->addLine(2, "<script type=\"text/javascript\">");
    $this->buffer->addLine(2, "//<![CDATA[");
    $this->buffer->addLine(2, "$(document).ready(function(){");
    
    
    foreach ($this->data as $gridId => $gridData) {
      $this->buffer->addLine(4, "$(\"#" . $gridId . "\").jqGrid({");
      $this->buffer->addLine(4, "url:'" . $gridData['dataSourceUri'] . "',");
      $this->buffer->addLine(4, "datatype: 'json',");
      $this->buffer->addLine(4, "mtype: 'POST',");
      $this->buffer->addLine(4, "colModel :[");
    
      foreach ($gridData['fields'] as $fieldId=>$field) {
        if ($gridData['defaultOrderFieldId'] === null) $gridData['defaultOrderFieldId'] = $field['name'];
        $line =  "{index:'" . $field['name'] . "'";
        $line .= ", name:'" . $fieldId . "'";
        $line .= ", label:'" . $field['label'] . "'";
        $line .= ", align:'" . $field['align'] . "'";
        if ($field['width'] !== null) $line .= ", width:" . $field['width'] . "";
        $line .= "},";
        $this->buffer->addLine(4, $line);
      }
    
      $this->buffer->addLine(4, "],");
      $this->buffer->addLine(4, "pager: $('#" . $gridId . "_pager'),");

      $this->buffer->addLine(4, "rowNum:" . $gridData['recordsPerPage'] . ",");
      $this->buffer->addLine(4, "height: '100%',");
      if (substr($gridData['width'],-1)=='%') {
        $this->buffer->addLine(4, "width: $(\"#" . $gridId . "\").parent().width() * " . substr($gridData['width'],0,-1) . " / 100 - " . $this->widthBorders .",");
      } else {
        $this->buffer->addLine(4, "width: " . $gridData['width'] . ",");
      }
      $this->buffer->addLine(4, "rowList:[" . $gridData['recordsPerPageList'] . "],");
      $this->buffer->addLine(4, "sortname: '" . $gridData['defaultOrderFieldId'] . "',");
      $this->buffer->addLine(4, "sortorder: '" . $gridData['defaultOrderDirection'] . "',");
      $this->buffer->addLine(4, "viewrecords: true,");
      //$this->buffer->addLine(4, "sopt:['eq','ne','lt','le','gt','ge','bw','bn','ew','en','cn','nc'],");
      
      if ($gridData['overrideSelect'] !== null) { //override del select
        $this->buffer->addLine(4, "onSelectRow: function(id){ window.location='" . $gridData['overrideSelect'] . "' + id;  },");
      }
      
      $this->buffer->addLine(4, "caption: '" . $gridData['title'] . "'");
      $this->buffer->addLine(4, "}).navGrid(\"#" . $gridId . "_pager\",{" . $this->_getPagerString($gridId) . "})");
      $this->buffer->addLine(4, ";"); 
      
      
      if ($gridData['overrideView'] !== null) { //override del view
        $this->buffer->addLine(2, "$(\"#view_" . $gridId . "\").unbind(\"click\").click(function() { var gr = jQuery(\"#" . $gridId . "\").getGridParam('selrow'); if( gr != null ) window.location='" . $gridData['overrideView'] . "' + gr; else $('#PRGR_dlgSeleccioneFila').dialog('open'); });");
      }
    }
    $this->buffer->addLine(4, "$('#PRGR_dlgSeleccioneFila').dialog({autoOpen: false});"); 
    $this->buffer->addLine(4, "});"); 

    //resize de la grilla
    $this->buffer->addLine(2, "$(window).bind('resize', function() {");
    foreach ($this->data as $gridId => $gridData) {
      if (substr($gridData['width'],-1)=='%') {
        $this->buffer->addLine(4, "$(\"#" . $gridId . "\").setGridWidth($(\"#" . $gridId . "\").parent().parent().parent().parent().width() * " . substr($gridData['width'],0,-1) . " / 100 - " . $this->widthBorders .");");
      }
    }
    $this->buffer->addLine(2, "});");
 
    $this->buffer->addLine(2, "//]]>");
    $this->buffer->addLine(2, "</script>");
    $this->buffer->addLine(2, "<div id=\"PRGR_dlgSeleccioneFila\" title=\"" . lang('pr_Atencion') . "\">" . lang('pr_DebeSeleccionarUnRegistro') . "</div>");
    
    if (count($this->actions) > 0) {
      $this->buffer->addLine(2, "<h2>" . lang('pr_Actions') . "</h2>");
      $this->buffer->addLine(2, "<div id=\"pageActions\">");
      foreach ($this->actions as $action) {
        if ($action[2] == '') {
          $this->buffer->addLine(4, "<span class=\"pageAction\">" . anchor($action[0],$action[1]) . "</span>");
        } else {
          $this->buffer->addLine(4, "<span class=\"pageAction\">" . anchor('#',$action[1],array("onclick"=> $action[2] )) . "</span>");
        }
      }
      $this->buffer->addLine(2, "</div>");
    }
    
    return $this->buffer->get();
  } //render
  
  private function _getPagerString ($gridId) {
    $out = "";
    foreach ($this->data[$gridId]['pager'] as $key=>$item) {
      if ($item === TRUE) { $out .= "$key:true, "; } else { $out .= "$key: false, "; }
    }
    $out = substr($out,0,-2);
    return ($out);
  }
  
}
